/**
 * MessageDispatcher.java
 * ************************** 
 * @date Mar 22, 2011
 * @author Michele Tamburini
 * 
 * **************************
 */
package rmitut;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author michele
 * 
 * 
 * Description: 
 *
 */
public class MessageDispatcher extends Thread {
	
	private Deque<Message> receivedMessages = new ArrayDeque<Message>();
	private Deque<Message> messagesToDispatch = new ArrayDeque<Message>();
	
//	private Vector<MessageHandler> messageHandlers = new Vector<MessageHandler>();
	
	private boolean hasToStop;
	
	public MessageDispatcher(Deque<Message> receivedMessages,
			Deque<Message> messagesToDispatch) {
		this.receivedMessages = receivedMessages;
		this.messagesToDispatch = messagesToDispatch;
	}

	public void run(){
		boolean running = true;
		while(running){
			try {
				if(!this.isInterrupted())
				synchronized (receivedMessages) {
					receivedMessages.wait(0);
					while(!receivedMessages.isEmpty()){
						messagesToDispatch.add(receivedMessages.pollFirst());
					}
					receivedMessages.notify();
				}
			} catch (InterruptedException e) {
				//				e.printStackTrace();
				if(hasToStop){
					running = false;
					System.out.println(getName()+ " I'm interrupted");
				}
			}
			
			/*here must executes the handler queue in order to find 
			for each message its own handler (and yet ServiceLevel to which
			deliver the message*/
		}
	}
	
	public void stopMessageDispatcher(){
		hasToStop = true;
		this.interrupt();
	}
	

}
